package com.example.ass7.animation;

import biuoop.DrawSurface;
import biuoop.GUI;
import biuoop.Sleeper;

/**
 * @author Meirav Ben Izhak
 */
public class AnimationRunner {
    private final GUI gui;
    private final Sleeper sleeper;
    private final int framesPerSecond;

    /**
     * @param sleeper
     *            sleeper
     * @param gui
     *            gui
     * @param framesPerSecond
     *            framesPerSecond
     */
    public AnimationRunner(
        Sleeper sleeper, GUI gui, int framesPerSecond) {
        this.gui = gui;
        this.sleeper = new biuoop.Sleeper();
        this.framesPerSecond = framesPerSecond;
    }

    /**
     * @param animation
     *            animation
     */
    public void run(Animation animation) {
        while (!animation.shouldStop()) {
            long startTime = System.currentTimeMillis(); // timing
            DrawSurface d = this.gui.getDrawSurface();

            double dt = 1.0 / this.framesPerSecond;
            animation.doOneFrame(d, dt);

            this.gui.show(d);
            long usedTime = System.currentTimeMillis()
                    - startTime;
            long milliSecondLeftToSleep = 10 - usedTime;
            if (milliSecondLeftToSleep > 0) {
                this.sleeper.sleepFor(milliSecondLeftToSleep);
            }
        }
    }

    /**
     * @return GUI
     */
    public GUI getGUI() {
        return this.gui;
    }
}